import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const Mine = () => import('@/views/mine')
const Edit = () => import('@/views/mine/edit.vue')
const Article = () => import('@/views/article')
const Search = () => import('@/views/search')
const Result = () => import('@/views/result')
const Chat = () => import('@/views/chat')
import store from '@/store/index.js' // store===this.$store
// import { Toast } from 'vant'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
    // component: () => import('@/views/login')
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/chat',
    component: Chat
  },
  {
    path: '/result/:q',
    component: Result,
    meta: {
      keep: true // 该路由缓存
    }
  },
  {
    path: '/article',
    component: Article
  },
  {
    path: '/mine/edit',
    component: Edit,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/',
    redirect: '/layout/home'
  },
  {
    path: '/layout',
    component: Layout,
    children: [
      {
        path: 'home',
        component: Home,
        meta: {
          keep: true // 该路由缓存
        }
        // 相对写法：不以/开头  /layout/home
        // 绝对写法：以/开头
      },
      {
        path: 'question',
        component: Question
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'mine',
        component: Mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置守卫
router.beforeEach((to, from, next) => {
  // to:想去的路由的路由信息
  // from:从哪来的路由信息
  // next() 正常通过
  // next('其它路由的path'):不允许通过，让你去其它路由
  // 注意点：去其它路由时，也还是要经过该导航守卫
  /*
   要去的页面是否需要登录
       需要登录
           判断是否有token
               有token(认为登录)
                   正常通过(next())
                无token
                   next('/login')
       不需要登录
           正常通过(next())   */

  // console.log('from', from)
  // console.log('to', to)
  if (to.meta.needLogin) {
    if (store.state.tokenObj.token) {
      next()
    } else {
      // Toast.fail('请先登录')
      Vue.prototype.$toast.fail('请先登录')
      next('/login?redirect=' + to.fullPath)
      // 路由传值  传  this.$router.push('/login?xxx=123')  next('/login?xxx=123')  收：this.$route.query.xxx
    }
  } else {
    next()
  }
})
// 后置守卫
router.afterEach((to, from) => {})
// 解决路由跳转错误问题
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

export default router
